package kordegi.forumsystem.controller;

import io.jsonwebtoken.lang.Assert;
import kordegi.forumsystem.common.lang.Result;
import kordegi.forumsystem.entity.Article;
import kordegi.forumsystem.entity.PageRequest;
import kordegi.forumsystem.entity.PageResult;
import kordegi.forumsystem.service.ArticleService;
import kordegi.forumsystem.service.Impl.ArticleServiceImpl;
import kordegi.forumsystem.util.ShiroUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * @author kordegi
 * @date 2022.05.01 17:00
 * @Description
 */

@RestController
public class ArticleController {
    @Autowired
    ArticleServiceImpl articleService;

    @RequestMapping("getArticle/{id}")
    public String getArticle(@PathVariable(name = "id") Long id) {
        return articleService.getById(id).toString();
    }

    @GetMapping("/articles")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {
        if (currentPage == null || currentPage < 1) currentPage = 1;
        PageRequest pageRequest = new PageRequest(currentPage, 5);
        return articleService.findByPager(pageRequest);
    }

    @GetMapping("/articles/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Article article = articleService.getById(id);
        Assert.notNull(article, "该文章已被删除");
        return Result.succ(article);
    }

    @GetMapping("/articles/edit")
    public Result edit(@Validated @RequestBody Article article) {
        Article temp = null;

        if (article.getId() != null) {//编辑
            temp = articleService.getById(article.getId());
            Assert.isTrue(temp.getUser_id() == ShiroUtil.getProfile().getId(), "没有权限修改");
        }else {//添加
            temp = new Article();
            temp.setUser_id(ShiroUtil.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }

        BeanUtils.copyProperties(article, temp, "id", "user_id", "created", "status");
        articleService.saveOrUpdate(article);
        return Result.succ("操作成功",null);
    }

}
